/* =========================================================
 * selectUser.js v0.3.12
 * =========================================================
 * 选择人员
 * ========================================================= */

;
(function($, window, document, undefined) {

	/*global jQuery, console*/

	'use strict';

	var pluginName = 'selectUser';

	var _default = {};

	var contactsObject = {};

	var options = {};

	var ajaxOptions = {};

	var tags = {};

	_default.options = {
		selectedModel: 0,
		defaultImgSrc: "img/default-icon.png",
		rangeModel: 0,
		getTenantsUrl: ""
	};

	var userList = function(element, options) {
		this.$element = $(element);
		this.elementId = element.id;

		this.init(options);

		return this;
	};

	// 初始化数据
	userList.prototype.init = function(options) {
		this.options = $.extend({}, _default.options, options);

		if(this.options.selectedModel == 0) {
			this.bindUserDoubleClick();
		} else {
			this.bindOrgCheck();
			this.bindUserCheck();
			this.bindRangeTenantCheck();
			this.bindRangeOrgCheck();
			this.bindSearchTenantKeyUp();
			this.bindSearchOrgKeyUp();
			this.bindSearchTenantClose();
			this.bindSearchOrgClose();
			this.bindSelectedTenantDelete();
			this.bindSelectedOrgDelete();
		}

		this.bindSearchKeyUp();
		this.bindOrgtoggle();
		this.bindSearchClose();
		this.bindSelectedUserDelete();
		this.initAjaxOptions();
	};

	// 初始化请求参数
	userList.prototype.initAjaxOptions = function() {
		this.ajaxOptions = {
			interfaceUrl: $.cookie("url_interface"),
			tenantId: $.cookie("C_TenantId"),
			companyId: $.cookie("C_CompanyId"),
			dataSource: $.cookie("C_DataSource"),
			currentUserId: $.cookie("C_id"),
			token: $.cookie("C_token")
		};

		//						this.ajaxOptions = {
		//							interfaceUrl: 'http://10.0.5.43:8888/',
		//							tenantId: 'cdafa3fe-e659-4fc9-82fa-2c8138d475eb',
		//							companyId: 'be3d6f30-fd75-4aae-97f0-98d4d2df45af',
		//							dataSource: 'DuDu2',
		//							currentUserId: '43768afc-4b88-4654-a556-117c0d2db83e',
		//							token: '098FFE3CF9733DF76C6C7BF5921EB6EA31F56896CEB3E63B587AF4CAE4054A7D'
		//						};
	}

	// 绘制
	userList.prototype.render = function() {

		if(!this.initialized) {

			// Setup first time only components
			//			this.$element.addClass(pluginName);
			//			this.$wrapper = $(this.template.list);

			//			this.injectStyle();

			this.initialized = true;
		}

		this.$element.empty();
		this.$element.addClass('wrapper wrapper-content animated fadeInRight');

		if(this.options.selectedModel == 2) {
			if(this.options.rangeModel == 1) {
				this.$element.append(['<div class="row">',
					'<div class="col-sm-12">',
					'<div class="tabs-container kd_persTabs1 ">',
					'<div class="tabs-left">',
					'<ul class="nav nav-tabs">',
					'<li class="active"><a data-toggle="tab" href="#tab-a1"> 门店</a></li>',
					'</ul>',
					'<div class="tab-content ">',
					'<div id="tab-a1" class="tab-pane active">',
					'<div class="panel-body row">',
					'<div class="col-sm-6">',
					'<div class="kd_persBody ">',
					'<div class="input-search">',
					'<i class="input-search-icon glyphicon glyphicon-search" aria-hidden="true"></i>',
					'<input type="text" class="form-control search-tenant" name="" placeholder="搜索门店">',
					'<button type="button" class="input-search-close btn-search-tenant" aria-label="Close"><i class="glyphicon glyphicon-remove"></i></button>',
					'</div>',
					'<div class="kd_search_body hidden">',
					'<ul class="kdpers_list">',
					'<li class="kdpers_errormsg hidden">请求失败</li>',
					'<li data-id="1" class="kdpers_parentnode">',
					'<div class="kdpers_title">',
					'<h5><span class="kdmini_parentname">总经办</span><em class="kdmini_nums">（3）</em></h5>',
					'<div class="kdpers_checkbox"><input type="checkbox" value=""> </div>',
					'</div>',
					'</li>',
					'<li data-id="2" class="kdpers_parentnode">',
					'<div class="kdpers_title">',
					'<h5><span class="kdmini_parentname">财务</span><em class="kdmini_nums">（2）</em></h5>',
					'<div class="kdpers_checkbox"><input type="checkbox" value=""> </div>',
					'</div>',
					'</li>',
					'</ul>',
					'</div>',
					'<div class="nav-tabs-horizontal">',
					'<ul class="kdpers_list">',
					'<li class="kdpers_errormsg hidden">请求失败</li>',
					'</ul>',
					'</div>',
					'</div>',
					'</div>',
					'<div class="col-sm-6">',
					'<div class="ibox float-e-margins">',
					'<div class="ibox-title">',
					'<h5>已选择门店</h5>',
					'</div>',
					'<div class="ibox-content no-padding">',
					'<div class="user_sept_group user_sept_group_tenant" style="height: 500px; overflow-y:scroll; padding-top:15px; padding-bottom:10px;">',
					'</div>',
					'</div>',
					'</div>',
					'</div>',
					'</div>',
					'</div>',
					'</div>',
					'</div>',
					'</div>',
					'</div>',
					'</div>'
				].join(""));
			} else {
				this.$element.append(['<div class="row">',
					'<div class="col-sm-12">',
					'<div class="tabs-container kd_persTabs1 ">',
					'<div class="tabs-left">',
					'<ul class="nav nav-tabs">',
					'<li class="active"><a data-toggle="tab" href="#tab-a1"> 门店</a></li>',
					'<li class=""><a data-toggle="tab" href="#tab-a2"> 部门</a></li>',
					'<li class=""><a data-toggle="tab" href="#tab-a3"> 联系人</a></li>',
					'</ul>',
					'<div class="tab-content ">',
					'<div id="tab-a1" class="tab-pane active">',
					'<div class="panel-body row">',
					'<div class="col-sm-6">',
					'<div class="kd_persBody ">',
					'<div class="input-search">',
					'<i class="input-search-icon glyphicon glyphicon-search" aria-hidden="true"></i>',
					'<input type="text" class="form-control search-tenant" name="" placeholder="搜索门店">',
					'<button type="button" class="input-search-close btn-search-tenant" aria-label="Close"><i class="glyphicon glyphicon-remove"></i></button>',
					'</div>',
					'<div class="kd_search_body hidden">',
					'<ul class="kdpers_list">',
					'<li class="kdpers_errormsg hidden">请求失败</li>',
					'<li data-id="1" class="kdpers_parentnode">',
					'<div class="kdpers_title">',
					'<h5><span class="kdmini_parentname">总经办</span><em class="kdmini_nums">（3）</em></h5>',
					'<div class="kdpers_checkbox"><input type="checkbox" value=""> </div>',
					'</div>',
					'</li>',
					'<li data-id="2" class="kdpers_parentnode">',
					'<div class="kdpers_title">',
					'<h5><span class="kdmini_parentname">财务</span><em class="kdmini_nums">（2）</em></h5>',
					'<div class="kdpers_checkbox"><input type="checkbox" value=""> </div>',
					'</div>',
					'</li>',
					'</ul>',
					'</div>',
					'<div class="nav-tabs-horizontal">',
					'<ul class="kdpers_list">',
					'<li class="kdpers_errormsg hidden">请求失败</li>',
					'</ul>',
					'</div>',
					'</div>',
					'</div>',
					'<div class="col-sm-6">',
					'<div class="ibox float-e-margins">',
					'<div class="ibox-title">',
					'<h5>已选择门店</h5>',
					'</div>',
					'<div class="ibox-content no-padding">',
					'<div class="user_sept_group user_sept_group_tenant" style="height: 500px; overflow-y:scroll; padding-top:15px; padding-bottom:10px;">',
					'</div>',
					'</div>',
					'</div>',
					'</div>',
					'</div>',
					'</div>',
					'<div id="tab-a2" class="tab-pane ">',
					'<div class="panel-body row">',
					'<div class="col-sm-6">',
					'<div class="kd_persBody ">',
					'<div class="input-search">',
					'<i class="input-search-icon glyphicon glyphicon-search" aria-hidden="true"></i>',
					'<input type="text" class="form-control search-org" name="" placeholder="搜索部门">',
					'<button type="button" class="input-search-close btn-search-org" aria-label="Close"><i class="glyphicon glyphicon-remove"></i></button>',
					'</div>',
					'<div class="kd_search_body hidden">',
					'<ul class="kdpers_list">',
					'<li class="kdpers_errormsg hidden">请求失败</li>',
					'<li data-id="1" class="kdpers_parentnode">',
					'<div class="kdpers_title">',
					'<h5><span class="kdmini_parentname">总经办</span><em class="kdmini_nums">（3）</em></h5>',
					'<div class="kdpers_checkbox"><input type="checkbox" value=""> </div>',
					'</div>',
					'</li>',
					'<li data-id="2" class="kdpers_parentnode">',
					'<div class="kdpers_title">',
					'<h5><span class="kdmini_parentname">财务</span><em class="kdmini_nums">（2）</em></h5>',
					'<div class="kdpers_checkbox"><input type="checkbox" value=""> </div>',
					'</div>',
					'</li>',
					'</ul>',
					'</div>',
					'<div class="nav-tabs-horizontal">',
					'<ul class="kdpers_list">',
					'<li class="kdpers_errormsg hidden">请求失败</li>',
					'</ul>',
					'</div>',
					'</div>',
					'</div>',
					'<div class="col-sm-6">',
					'<div class="ibox float-e-margins">',
					'<div class="ibox-title">',
					'<h5>已选择部门</h5>',
					'</div>',
					'<div class="ibox-content no-padding">',
					'<div class="user_sept_group user_sept_group_org" style="height: 500px; overflow-y:scroll; padding-top:15px; padding-bottom:10px;">',
					'</div>',
					'</div>',
					'</div>',
					'</div>',
					'</div>',
					'</div>',
					'<div id="tab-a3" class="tab-pane ">',
					'<div class="panel-body row">',
					'<div class="col-sm-6">',
					'<div class="kd_persBody">',
					'<div class="input-search">',
					'<i class="input-search-icon glyphicon glyphicon-search" aria-hidden="true"> </i>',
					'<input type="text" class="form-control search" placeholder="搜索门店/岗位/姓名/手机号/群组">',
					'<button type="button" class="input-search-close btn-serach" aria-label="Close"><i class="glyphicon glyphicon-remove"> </i></button>',
					'</div>',
					'<div class="kd_search_body hidden">',
					'<ul class="kdpers_list">',
					'<li class="kdpers_errormsg hidden">请求失败</li>',
					'<ul class="kdpers_chatlist"></ul>',
					'</ul>',
					'</div>',
					'<div class="nav-tabs-horizontal">',
					'<ul class="nav nav-tabs nav-tabs-line kd_parent">',
					'<li class="kd_child active">',
					'<a data-toggle="tab" href="#tab-1" aria-expanded="true"> 本店</a>',
					'</li>',
					'<li class="kd_child">',
					'<a data-toggle="tab" href="#tab-2" aria-expanded="false">其他</a>',
					'</li>',
					'</ul>',
					'<div class="tab-content">',
					'<div id="tab-1" class="tab-pane active">',
					'<ul class="kdpers_list">',
					'<li class="kdpers_errormsg hidden">请求失败</li>',
					'</ul>',
					'</div>',
					'<div id="tab-2" class="tab-pane">',
					'<ul class="kdpers_list">',
					'<li class="kdpers_errormsg hidden">请求失败</li>',
					'</ul>',
					'</div>',
					'</div>',
					'</div>',
					'</div>',
					'</div>',
					'<div class="col-sm-6">',
					'<div class="ibox float-e-margins">',
					'<div class="ibox-title">',
					'<h5>已选择人员</h5>',
					'</div>',
					'<div class="ibox-content no-padding">',
					'<div class="user_sept_group user_sept_group_user" style="height: 500px; overflow-y:scroll; padding-top:15px; padding-bottom:10px;">',
					'</div>',
					'</div>',
					'</div>',
					'</div>',
					'</div>',
					'</div>',
					'</div>',
					'</div>',
					'</div>',
					'</div>',
					'</div>'
				].join(""));
			}
		} else {
			this.$element.append(['<div class="row">',
				'<div class="col-sm-6">',
				'<div class="kd_persBody">',
				'<div class="input-search">',
				'<i class="input-search-icon glyphicon glyphicon-search" aria-hidden="true"> </i>',
				'<input type="text" class="form-control search" placeholder="搜索门店/岗位/姓名/手机号/群组">',
				'<button type="button" class="input-search-close btn-serach" aria-label="Close"><i class="glyphicon glyphicon-remove"> </i></button>',
				'</div>',
				'<div class="kd_search_body hidden">',
				'<ul class="kdpers_list">',
				'<li class="kdpers_errormsg hidden">请求失败</li>',
				'<ul class="kdpers_chatlist"></ul>',
				'</ul>',
				'</div>',
				'<div class="nav-tabs-horizontal">',
				'<ul class="nav nav-tabs nav-tabs-line kd_parent">',
				'<li class="kd_child active">',
				'<a data-toggle="tab" href="#tab-1" aria-expanded="true"> 本店</a>',
				'</li>',
				'<li class="kd_child">',
				'<a data-toggle="tab" href="#tab-2" aria-expanded="false">其他</a>',
				'</li>',
				'</ul>',
				'<div class="tab-content">',
				'<div id="tab-1" class="tab-pane active">',
				'<ul class="kdpers_list">',
				'<li class="kdpers_errormsg hidden">请求失败</li>',
				'</ul>',
				'</div>',
				'<div id="tab-2" class="tab-pane">',
				'<ul class="kdpers_list">',
				'<li class="kdpers_errormsg hidden">请求失败</li>',
				'</ul>',
				'</div>',
				'</div>',
				'</div>',
				'</div>',
				'</div>',
				'<div class="col-sm-6">',
				'<div class="ibox float-e-margins">',
				'<div class="ibox-title">',
				'<h5>已选择人员</h5>',
				'</div>',
				'<div class="ibox-content no-padding">',
				'<div class="user_sept_group user_sept_group_user" style="height: 500px; overflow-y:scroll; padding-top:15px; padding-bottom:10px;">',
				'</div>',
				'</div>',
				'</div>',
				'</div>',
				'</div>'
			].join(""));
		}

	};

	// 显示选择人员
	userList.prototype.showSelectUser = function(selectedUsers, tags, disableUsers, tenantId) {
		this.selectedUsers = selectedUsers || [];
		this.disableUsers = disableUsers || [];
		this.tags = tags;
		this.options.tenantId = tenantId || '';
		this.render();

		if(this.options.selectedModel == 2) {
			this.getTenants();
			this.getOrgs();
		}

		this.getUsers();
		this.options.layerIndex = layer.open({
			type: 1,
			title: this.options.selectedModel == 2 ? '选择范围' : '选择人员',
			area: this.options.selectedModel == 2 ? ['70%', '90%'] : ['70%', '90%'],
			shadeClose: false, //点击遮罩关闭
			closeBtn: 0, //关闭按钮
			content: this.$element,
			btn: this.options.selectedModel == 0 ? ['取消'] : ['确定', '取消'],
			yes: this.confirm.bind(this),
			end: this.close.bind(this)
		});
	}

	// 设置已经选择人员列表
	userList.prototype.setSelectedUser = function(i, ele) {
		if($(ele).find('input[type=checkbox]').is(':checked') == true) {
			var accountId = $(ele).data('id');
			if(!this.inSelectedUser(accountId)) {
				this.selectedUsers.push({
					id: accountId,
					name: $(ele).data('name')
				});
			}
		}
	};

	// 确定选择人员
	userList.prototype.confirm = function(index, layero) {
		// 获取所有选择项
		this.selectedUsers = [];

		if(this.options.selectedModel == 2) {
			var rangType = 0;
			var rangTypeName = this.$element.find('.tabs-left .nav-tabs .active a').html();
			console.log(rangTypeName);
			if(rangTypeName == ' 门店') {
				rangType = 0;
				this.$element.find('#tab-a1 .nav-tabs-horizontal .kdpers_parentnode[data-id!=0]').each(this.setSelectedUser.bind(this));
			}

			if(rangTypeName == ' 部门') {
				rangType = 1;
				this.$element.find('#tab-a2 .nav-tabs-horizontal .kdpers_parentnode[data-id!=0]').each(this.setSelectedUser.bind(this));
			}

			if(rangTypeName == ' 联系人') {
				rangType = 2;
				// 本店选择人员
				this.$element.find('#tab-1 .kdpers_chatlist li').each(this.setSelectedUser.bind(this));

				// 其他选择人员
				this.$element.find('#tab-2 .kdpers_chatlist li').each(this.setSelectedUser.bind(this));

				// 搜索选择人员
				this.$element.find('.kd_search_body .kdpers_chatlist li').each(this.setSelectedUser.bind(this));
			}
			console.log(rangType);
			if(this.options.success) {
				this.options.success(this.selectedUsers, this.tags, rangType);
			}
		} else {
			// 本店选择人员
			this.$element.find('#tab-1 .kdpers_chatlist li').each(this.setSelectedUser.bind(this));

			// 其他选择人员
			this.$element.find('#tab-2 .kdpers_chatlist li').each(this.setSelectedUser.bind(this));

			// 搜索选择人员
			this.$element.find('.kd_search_body .kdpers_chatlist li').each(this.setSelectedUser.bind(this));

			if(this.options.success) {
				this.options.success(this.selectedUsers, this.tags);
			}
		}

		layer.close(index); //如果设定了yes回调，需进行手工关闭
	};

	// 关闭选择人员对话框
	userList.prototype.close = function(index) {
		if(this.options.end) {
			this.options.end();
		}
	};

	// 指定用户是否在已选择列表中
	userList.prototype.inSelectedUser = function(accountId) {
		for(var i = this.selectedUsers.length - 1; i >= 0; i--) {
			if(this.selectedUsers[i].id == accountId) {
				return true;
			}
		};
		return false;
	};

	// 指定用户是否在排除列表中
	userList.prototype.inDisableUsers = function(accountId) {
		for(var i = this.disableUsers.length - 1; i >= 0; i--) {
			if(this.disableUsers[i].id == accountId) {
				return true;
			}
		};
		return false;
	};

	// 添加选择人员列表
	userList.prototype.addFromSelectedUser = function(accountId, addFromSelectedUserCompleted) {
		console.log('addFromSelectedUser:accountId:' + accountId)
		if(this.inSelectedUser(accountId) == false) {
			this.selectedUsers.push({
				id: accountId,
				name: ''
			});

			if(addFromSelectedUserCompleted) {
				addFromSelectedUserCompleted(accountId);
			}
		}
		return false;
	};

	// 删除选择人员列表
	userList.prototype.removeFromSelectedUser = function(accountId, removeFromSelectedUserCompleted) {
		for(var i = this.selectedUsers.length - 1; i >= 0; i--) {
			if(this.selectedUsers[i].id == accountId) {
				this.selectedUsers.splice(i, 1);

				if(removeFromSelectedUserCompleted) {
					removeFromSelectedUserCompleted(accountId);
				}

				return true;
			}
		};
		return false;
	};

	userList.prototype.getUsersAjaxLoaded = function(json) {
		console.log(" get mendian");
		console.log(json);
		//window.location.href = '/sao/NewFileList';

		contactsObject.account = '43768afc-4b88-4654-a556-117c0d2db83e';
		contactsObject.friends = [];
		contactsObject.qita = [];
		//构造用户的好友列表数据
		if(json.statu === 1) {
			if(json.result && json.result.TenantUsers) {
				if(json.result.TenantUsers.Users) {
					var arr = json.result.TenantUsers.Users;
					for(var i = 0; i < arr.length; i++) {
						contactsObject.friends.push({
							account: arr[i].Id,
							createTime: "",
							gender: arr[i].Gender,
							nick: arr[i].UserName,
							updateTime: "",
							pos: arr[i].Position,
							Position: arr[i].Position,
							Organization: arr[i].Organization == "" ? json.result.TenantUsers.Name : arr[i].Organization,
							HeadImgAddress: arr[i].HeadImgAddress,
							birth: arr[i].Birthday,
							tel: arr[i].Mobile,
							Tenant: json.result.TenantUsers.Name,
							LoginName: arr[i].LoginName
						});
					}
				}
			}

			//构造用户的 其他模块的数据
			if(json.result && json.result.Friends) {
				for(var j = 0; j < json.result.Friends.length; j++) {
					var temp_obj = json.result.Friends[j];
					for(var k = 0; k < temp_obj.Users.length; k++) {

						var temp = temp_obj.Users[k];
						contactsObject.qita.push({
							account: temp.Id,
							createTime: "",
							gender: temp.Gender,
							nick: temp.UserName,
							updateTime: "",
							pos: temp.Position,
							Position: temp.Position,
							Organization: temp.Organization == "" ? temp_obj.Name : temp.Organization,
							HeadImgAddress: temp.HeadImgAddress,
							birth: temp.Birthday,
							tel: temp.Mobile,
							Tenant: temp_obj.Name,
							LoginName: temp.LoginName,
							BrandName: temp_obj.BrandName
						});
					}
				}
			}

			this.displayUserInfo(contactsObject.friends, this.$element.find('#tab-1 .kdpers_list'));
			this.displayQitaUserInfo(contactsObject.qita, this.$element.find('#tab-2 .kdpers_list'));

			this.displaySelectedUser();
		} else {
			alert(json.result);
			//delCookie('uid');
			//delCookie('sdktoken');
			//window.location.href = '/sao/scan';
		}
	};

	userList.prototype.getTenantsAjaxLoaded = function(json) {
		console.log(" get Tenants");
		console.log(json);
		//window.location.href = '/sao/NewFileList';

		contactsObject.tenants = [];
		//构造用户的好友列表数据
		if(json.statu === 1) {
			if(json.result) {
				var arr = json.result;
				for(var i = 0; i < arr.length; i++) {
					contactsObject.tenants.push({
						id: arr[i].Id,
						name: arr[i].Name,
					});
				}
				this.displayRangeInfo(contactsObject.tenants, this.$element.find('#tab-a1 .nav-tabs-horizontal'));
				this.displaySelectedTenant();
			}
		} else {
			alert(json.result);
			//delCookie('uid');
			//delCookie('sdktoken');
			//window.location.href = '/sao/scan';
		}
	};

	userList.prototype.getOrgsAjaxLoaded = function(json) {
		console.log(" get Orgs");
		console.log(json);
		//window.location.href = '/sao/NewFileList';

		contactsObject.orgs = [];
		//构造用户的好友列表数据
		if(json.statu === 1) {
			if(json.result && json.result.Orgs) {
				var arr = json.result.Orgs;
				for(var i = 0; i < arr.length; i++) {
					contactsObject.orgs.push({
						id: arr[i].Id,
						name: arr[i].Name,
					});
				}
				this.displayRangeInfo(contactsObject.orgs, this.$element.find('#tab-a2 .nav-tabs-horizontal'));
			}
		} else {
			alert(json.result);
			//delCookie('uid');
			//delCookie('sdktoken');
			//window.location.href = '/sao/scan';
		}
	};

	// 显示区域信息
	userList.prototype.displayRangeInfo = function(rangeInfos, $kdpers_list) {
		var list = rangeInfos,
			info,
			html = '';

		html += ['<ul class="kdpers_list">',
			'<li data-id="0" class="kdpers_parentnode">',
			'<div class="kdpers_title">',
			'<h5><span class="kdmini_parentname">全选</span></h5>',
			'<div class="kdpers_checkbox"><input type="checkbox" value=""> </div>',
			'</div>',
			'</li>',
		].join("");

		for(var i = 0; i < list.length; i++) {
			info = list[i];

			html += ['<li data-id="' + info.id + '" data-name="' + info.name + '" class="kdpers_parentnode">',
				'<div class="kdpers_title">',
				'<h5><span class="kdmini_parentname">' + info.name + '</span></h5>',
				'<div class="kdpers_checkbox"><input type="checkbox" value=""> </div>',
				'</div>',
				'</li>'
			].join("");

		}

		html += "</ul>";

		$kdpers_list.empty();
		$kdpers_list.append(html);
		if(this.options.selectedModel == 2 && this.options.rangeModel == 1) {
			$kdpers_list.find('.kdpers_parentnode').each(this.eachRange.bind(this));
		}
	};

	// 显示人员信息
	userList.prototype.displayUserInfo = function(userInfos, $kdpers_list) {
		var list = userInfos,
			info,
			html = '',
			userHtml = '',
			disableUserCount = 0;

		var orgGroupArr = {};
		for(var j = 0; j < list.length; j++) {
			var info2 = list[j];
			if(orgGroupArr[info2.Organization]) {
				orgGroupArr[info2.Organization].push(info2);
			} else {
				orgGroupArr[info2.Organization] = new Array();
				orgGroupArr[info2.Organization].push(info2);
			}
		}

		var i = 0;
		for(var prop in orgGroupArr) {
			i++;
			var groupName = prop;
			var groupArr = orgGroupArr[prop];

			disableUserCount = 0;
			userHtml = '';
			for(var k = 0; k < groupArr.length; k++) {
				info = groupArr[k];
				if(groupArr[k].account !== userInfos.account && !this.inDisableUsers(groupArr[k].account)) {
					var imgSrc = "";
					if(info.HeadImgAddress && info.HeadImgAddress !== "") {
						imgSrc = info.HeadImgAddress;
					} else {
						imgSrc = this.options.defaultImgSrc;
					}
					userHtml += ['<li data-id="' + info.account + '" data-name="' + info.nick + '" class="kdmini_childnode" type="one">',
						'<a class="kdpers_oneface"><img src="' + imgSrc + '" ></a>',
						'<div class="kdpers_onename">',
						'<h4><span>' + info.nick + '</span></h4>',
						'<p>' + info.Position + '</p>',
						'</div>',
						'<div class="kdpers_checkbox"><input type="checkbox" value=""> </div>',
						'</li>'
					].join("");
				} else {
					disableUserCount++;
				}
			}

			html += ['<li data-id="' + i + '" class="kdpers_parentnode">',
				'<div class="kdpers_title">',
				'<h5><i class="fa fa-caret-right"></i><span class="kdmini_parentname">' + groupName + '</span><span class="kdmini_nums">（' + (groupArr.length - disableUserCount) + '）</span></h5>',
				'<div class="kdpers_checkbox"><input type="checkbox" value=""> </div>', // 处理选中状态
				'</div>',
				'<ul class="kdpers_chatlist hidden">'
			].join("");
			html += userHtml;
			html += "</ul>";
			html += "</li>";
		}
		$kdpers_list.empty();
		$kdpers_list.append(html);
		if(this.options.selectedModel == 0) {
			$kdpers_list.find('.kdpers_checkbox').each(function(i, ele) {
				$(this).addClass('hidden');
			});
		} else {
			$kdpers_list.find('.kdpers_parentnode').each(this.eachOrg.bind(this));
		}
	}

	// 显示其他人员信息
	userList.prototype.displayQitaUserInfo = function(userInfos, $kdpers_list) {
		var list = userInfos,
			info,
			html = '',
			userHtml = '',
			disableUserCount = 0;
		var groupName = '';
		var orgGroupArr = {};
		for(var j = 0; j < list.length; j++) {
			var info2 = list[j];
			groupName = info2.BrandName + '-' + info2.Tenant;
			if(orgGroupArr[groupName]) {
				orgGroupArr[groupName].push(info2);
			} else {
				orgGroupArr[groupName] = new Array();
				orgGroupArr[groupName].push(info2);
			}
		}

		var i = 0;
		for(var prop in orgGroupArr) {
			i++;
			groupName = prop;
			var groupArr = orgGroupArr[prop];

			disableUserCount = 0;
			userHtml = '';
			for(var k = 0; k < groupArr.length; k++) {
				info = groupArr[k];
				if(groupArr[k].account !== userInfos.account && !this.inDisableUsers(groupArr[k].account)) {
					var imgSrc = "";
					if(info.HeadImgAddress && info.HeadImgAddress !== "") {
						imgSrc = info.HeadImgAddress;
					} else {
						imgSrc = this.options.defaultImgSrc;
					}
					userHtml += ['<li data-id="' + info.account + '" data-name="' + info.nick + '" class="kdmini_childnode" type="one">',
						'<a class="kdpers_oneface"><img src="' + imgSrc + '" ></a>',
						'<div class="kdpers_onename">',
						'<h4><span>' + info.nick + '</span></h4>',
						'<p>' + info.Position + '</p>',
						'</div>',
						'<div class="kdpers_checkbox"><input type="checkbox" value=""> </div>',
						'</li>'
					].join("");
				} else {
					disableUserCount++;
				}

			}

			html += ['<li data-id="' + i + '" class="kdpers_parentnode">',
				'<div class="kdpers_title">',
				'<h5><i class="fa fa-caret-right"></i><span class="kdmini_parentname">' + groupName + '</span><em class="kdmini_nums">（' + (groupArr.length - disableUserCount) + '）</em></h5>',
				'<div class="kdpers_checkbox"><input type="checkbox" value=""> </div>', // 处理选中状态
				'</div>',
				'<ul class="kdpers_chatlist hidden">'
			].join("");
			html += userHtml;
			html += "</ul>";
			html += "</li>";
		}
		$kdpers_list.empty();
		$kdpers_list.append(html);
		if(this.options.selectedModel == 0) {
			$kdpers_list.find('.kdpers_checkbox').each(function(i, ele) {
				$(this).addClass('hidden');
			});
		} else {
			$kdpers_list.find('.kdpers_parentnode').each(this.eachOrg.bind(this));
		}
	}

	// 显示搜索人员信息
	userList.prototype.displaySearchUserInfo = function(userInfos, $kdpers_list) {
		var list = userInfos,
			info,
			html = '';

		html += ['<ul class="kdpers_chatlist">'].join("");

		for(var i = 0; i < userInfos.length; i++) {
			info = userInfos[i];
			if(info.account !== userInfos.account && !this.inDisableUsers(info.account)) {
				var imgSrc = "";
				if(info.HeadImgAddress && info.HeadImgAddress !== "") {
					imgSrc = info.HeadImgAddress;
				} else {
					imgSrc = this.options.defaultImgSrc;
				}
				html += ['<li data-id="' + info.account + '" data-name="' + info.nick + '" class="kdmini_childnode" type="one">',
					'<a class="kdpers_oneface"><img src="' + imgSrc + '" ></a>',
					'<div class="kdpers_onename">',
					'<h4><span>' + info.nick + (info.Position == '' ? '' : '(' + info.Position + ')') + '</span></h4>',
					'<p>' + info.Tenant + '</p>',
					'</div>',
					'<div class="kdpers_checkbox"><input type="checkbox" value=""> </div>',
					'</li>'
				].join("");
			}
		}

		html += "</ul>";

		$kdpers_list.empty();

		if(userInfos.length == 0) {
			$kdpers_list.append('<li class="kdpers_errormsg">未找到相关人员</li>');
		} else {
			this.$element.find('.nav-tabs-horizontal').addClass('hidden');
			this.$element.find('.kd_search_body').removeClass('hidden');
			$kdpers_list.append(html);
			if(this.options.selectedModel == 0) {
				$kdpers_list.find('.kdpers_checkbox').each(function(i, ele) {
					$(this).addClass('hidden');
				});
			} else {
				$kdpers_list.find('.kdpers_chatlist li').each(this.eachUser.bind(this));
			}
		}
	};

	// 显示已勾选用户
	userList.prototype.displaySelectedUser = function() {
		for(var i = 0; i < this.selectedUsers.length; i++) {
			this.addUserToSelectedUsers(this.selectedUsers[i].id);
		}
	};

	// 显示已勾选门店
	userList.prototype.displaySelectedTenant = function() {
		for(var i = 0; i < this.selectedUsers.length; i++) {
			this.addTenantToSelectedTenants(this.selectedUsers[i].id);
		}
	};

	// 遍历部门勾选已选择项
	userList.prototype.eachOrg = function(i, ele) {
		$(ele).find('.kdpers_chatlist li').each(this.eachUser.bind(this));
	};

	// 遍历范围勾选已选择项
	userList.prototype.eachRange = function(i, ele) {
		var id = $(ele).data('id');
		if(this.inSelectedUser(id)) {
			if($(ele).find('input[type=checkbox]').is(':checked') == false) {
				$(ele).find('input[type=checkbox]').click();
			}
		}
	};

	// 遍历人员勾选已选择项
	userList.prototype.eachUser = function(i, ele) {
		var id = $(ele).data('id');
		if(this.inSelectedUser(id)) {
			if($(ele).find('input[type=checkbox]').is(':checked') == false) {
				$(ele).find('input[type=checkbox]').click();
			}
		}
	};

	// 获取人员列表
	userList.prototype.getUsers = function() {
		$.ajax({
			cache: false,
			url: this.ajaxOptions.interfaceUrl + "mCommon/getUsersOrTenants",
			type: "POST",
			//contentType: "application/x-www-form-urlencoded",
			//tenantId=&companyId=&osType=&dataSource=&versionCode=&currentUserId=&token=&gettype=
			data: {
				tenantId: this.ajaxOptions.tenantId,
				companyId: this.ajaxOptions.companyId,
				dataSource: this.ajaxOptions.dataSource,
				iv: "2",
				versionCode: 1,
				osType: "3",
				currentUserId: this.ajaxOptions.currentUserId,
				token: this.ajaxOptions.token,
				gettype: 1,

				_: new Date().getTime()
			},
			dataType: "json",
			async: true,
			success: this.getUsersAjaxLoaded.bind(this),
			error: function(e) {
				//console.log(e);
				//console.log('fail');
			}
		});
	};

	// 获取门店信息
	userList.prototype.getTenants = function() {
		if(this.options.rangeModel == 1) {
			$.ajax({
				cache: false,
				url: this.options.getTenantsUrl,
				type: "POST",
				//contentType: "application/x-www-form-urlencoded",
				//tenantId=&companyId=&osType=&dataSource=&versionCode=&currentUserId=&token=&gettype=
				data: {
					tenantId: this.options.tenantId,
					companyId: this.ajaxOptions.companyId,
					dataSource: this.ajaxOptions.dataSource,
					iv: "2",
					versionCode: 1,
					osType: "3",
					currentUserId: this.ajaxOptions.currentUserId,
					token: this.ajaxOptions.token,
					_: new Date().getTime()
				},
				dataType: "json",
				async: true,
				success: this.getTenantsAjaxLoaded.bind(this),
				error: function(e) {
					//console.log(e);
					//console.log('fail');
				}
			});
		} else {
			$.ajax({
				cache: false,
				url: this.ajaxOptions.interfaceUrl + "mCommon/getTenants",
				type: "POST",
				//contentType: "application/x-www-form-urlencoded",
				//tenantId=&companyId=&osType=&dataSource=&versionCode=&currentUserId=&token=&gettype=
				data: {
					tenantId: this.ajaxOptions.tenantId,
					companyId: this.ajaxOptions.companyId,
					dataSource: this.ajaxOptions.dataSource,
					iv: "2",
					versionCode: 1,
					osType: "3",
					currentUserId: this.ajaxOptions.currentUserId,
					token: this.ajaxOptions.token,
					_: new Date().getTime()
				},
				dataType: "json",
				async: true,
				success: this.getTenantsAjaxLoaded.bind(this),
				error: function(e) {
					//console.log(e);
					//console.log('fail');
				}
			});
		}
	};

	// 获取部门信息
	userList.prototype.getOrgs = function() {
		$.ajax({
			cache: false,
			url: this.ajaxOptions.interfaceUrl + "Notice/GetOrgsForCreateNotice",
			type: "POST",
			//contentType: "application/x-www-form-urlencoded",
			//tenantId=&companyId=&osType=&dataSource=&versionCode=&currentUserId=&token=&gettype=
			data: {
				tenantId: this.ajaxOptions.tenantId,
				companyId: this.ajaxOptions.companyId,
				dataSource: this.ajaxOptions.dataSource,
				iv: "1",
				versionCode: 1,
				osType: "3",
				currentUserId: this.ajaxOptions.currentUserId,
				token: this.ajaxOptions.token,
				_: new Date().getTime()
			},
			dataType: "json",
			async: true,
			success: this.getOrgsAjaxLoaded.bind(this),
			error: function(e) {
				//console.log(e);
				//console.log('fail');
			}
		});
	};

	// 搜索人员列表请求成功处理方法
	userList.prototype.searchUsersAjaxLoaded = function(json) {
		contactsObject.search = [];
		//构造搜索列表数据
		if(json.statu === 1) {
			if(json.result && json.result.Users) {
				if(json.result.Users) {
					var arr = json.result.Users;
					for(var i = 0; i < arr.length; i++) {
						contactsObject.search.push({
							account: arr[i].Id,
							createTime: "",
							gender: arr[i].Gender,
							nick: arr[i].UserName,
							updateTime: "",
							pos: arr[i].Position,
							Position: arr[i].Position,
							Organization: arr[i].Organization == "" ? arr[i].TenantName : arr[i].Organization,
							HeadImgAddress: arr[i].HeadImgAddress,
							birth: arr[i].Birthday,
							tel: arr[i].Mobile,
							Tenant: arr[i].TenantName,
							LoginName: arr[i].LoginName
						});
					}
				}
			}
			//			console.log(contactsObject);
			this.displaySearchUserInfo(contactsObject.search, $('.kd_search_body .kdpers_list'));
		} else {
			alert(json.result);
			//delCookie('uid');
			//delCookie('sdktoken');
			//window.location.href = '/sao/scan';
		}
	};

	// 搜索人员列表
	userList.prototype.searchUsers = function(e) {
		var searchKey = this.$element.find('.search').val();
		if(searchKey == '') {
			this.$element.find('.nav-tabs-horizontal').removeClass('hidden');
			this.$element.find('.kd_search_body').addClass('hidden');

			this.$element.find('#tab-1 .kdpers_list').find('.kdpers_parentnode').each(this.eachOrg.bind(this));
			this.$element.find('#tab-2 .kdpers_list').find('.kdpers_parentnode').each(this.eachOrg.bind(this));

			return;
		}
		$.ajax({
			cache: false,
			url: this.ajaxOptions.interfaceUrl + "mCommon/GetUserBySearch",
			type: "POST",
			//contentType: "application/x-www-form-urlencoded",
			//tenantId=&companyId=&osType=&dataSource=&versionCode=&currentUserId=&token=&gettype=
			data: {
				tenantId: this.ajaxOptions.tenantId,
				companyId: this.ajaxOptions.companyId,
				dataSource: this.ajaxOptions.dataSource,
				iv: "1",
				versionCode: 1,
				osType: "3",
				currentUserId: this.ajaxOptions.currentUserId,
				token: this.ajaxOptions.token,
				gettype: 1,
				page: 1,
				rows: 20,
				search: searchKey,
				_: new Date().getTime()
			},
			dataType: "json",
			async: true,
			success: this.searchUsersAjaxLoaded.bind(this),
			error: function(e) {
				//console.log(e);
				//console.log('fail');
			}
		});
	};

	// 绑定人员搜索框事件
	userList.prototype.bindSearchKeyUp = function() {
		this.$element.on('keyup', '.search', this.searchUsers.bind(this));
	};

	// 绑定门店搜索框按钮事件
	userList.prototype.bindSearchOrgKeyUp = function() {
		this.$element.on('keyup', '.search-org', function(e) {
			e.preventDefault();
			var searchKeyword = $(this).val();
			$(this).parents('.kd_persBody').find('.nav-tabs-horizontal .kdpers_parentnode[data-id!=0]').each(function() {
				var tenantName = $(this).find('.kdmini_parentname').html();
				if(tenantName.indexOf(searchKeyword) == -1) {
					$(this).hide();
				} else {
					$(this).show();
				}
			});
		});
	};

	// 绑定门店搜索框事件
	userList.prototype.bindSearchTenantKeyUp = function() {
		this.$element.on('keyup', '.search-tenant', function(e) {
			e.preventDefault();
			var searchKeyword = $(this).val();
			console.log(searchKeyword);
			$(this).parents('.kd_persBody').find('.nav-tabs-horizontal .kdpers_parentnode[data-id!=0]').each(function() {
				var tenantName = $(this).find('.kdmini_parentname').html();
				if(tenantName.indexOf(searchKeyword) == -1) {
					$(this).hide();
				} else {
					$(this).show();
				}
			});
		});
	};

	// 绑定点击部门按钮事件
	userList.prototype.bindOrgCheck = function() {
		this.$element.on('click', '#tab-1 .kdpers_title .kdpers_checkbox input[type=checkbox]', this.orgCheck.bind(this));
		this.$element.on('click', '#tab-2 .kdpers_title .kdpers_checkbox input[type=checkbox]', this.orgCheck.bind(this));
	};

	// 绑定范围选择门店点击事件
	userList.prototype.bindRangeTenantCheck = function() {
		this.$element.on('click', '#tab-a1 .kdpers_title .kdpers_checkbox input[type=checkbox]', this.rangeTenantCheck.bind(this));

		this.$element.on('click', '#tab-a1 .kdpers_parentnode', function(e) {
			$(this).find('input[type=checkbox]').click();
		});
	};

	// 绑定范围选择部门选择事件
	userList.prototype.bindRangeOrgCheck = function() {
		this.$element.on('click', '#tab-a2 .kdpers_title .kdpers_checkbox input[type=checkbox]', this.rangeOrgCheck.bind(this));

		this.$element.on('click', '#tab-a2 .kdpers_parentnode', function(e) {
			$(this).find('input[type=checkbox]').click();
		});
	};

	// 范围选择门店点击事件
	userList.prototype.rangeTenantCheck = function(e) {
		e.stopPropagation();
		var checked = $(e.target).is(':checked');
		var allChecked = true;

		var id = $(e.target).parents('.kdpers_parentnode').data('id');

		if(id == '0') {
			if(checked == true) {
				$(e.target).parents('.kdpers_list').find('.kdpers_parentnode').each(function(i, ele) {
					if($(ele).data('id') != '0' && $(ele).find('input[type=checkbox]').is(':checked') == false) {
						$(ele).find('input[type=checkbox]').click();
					}
				});
			} else {
				$(e.target).parents('.kdpers_list').find('.kdpers_parentnode').each(function(i, ele) {
					if($(ele).data('id') != '0' && $(ele).find('input[type=checkbox]').is(':checked') == true) {
						$(ele).find('input[type=checkbox]').click();
					}
				});
			}
		} else {
			if(checked == true) {
				$(e.target).parents('.kdpers_list').find('.kdpers_parentnode').each(function(i, ele) {
					if($(ele).data('id') != '0' && $(ele).find('input[type=checkbox]').is(':checked') == false) {
						allChecked = false;
						return;
					}
				});

				if(allChecked == true) {
					$(e.target).parents('.kdpers_list').find('.kdpers_parentnode[data-id=0] input[type=checkbox]').prop("checked", true);
				}
				this.addFromSelectedUser($(e.target).parents('.kdpers_parentnode').data('id'), this.addTenantToSelectedTenants.bind(this));
			} else {
				$(e.target).parents('.kdpers_list').find('.kdpers_parentnode[data-id=0] input[type=checkbox]').prop("checked", false);
				this.removeFromSelectedUser($(e.target).parents('.kdpers_parentnode').data('id'), this.removeTenantToSelectedTenants.bind(this));
			}
		}

	};

	// 范围选择门店点击事件
	userList.prototype.rangeOrgCheck = function(e) {
		e.stopPropagation();
		var checked = $(e.target).is(':checked');
		var allChecked = true;

		var id = $(e.target).parents('.kdpers_parentnode').data('id');

		if(id == '0') {
			if(checked == true) {
				$(e.target).parents('.kdpers_list').find('.kdpers_parentnode').each(function(i, ele) {
					if($(ele).data('id') != '0' && $(ele).find('input[type=checkbox]').is(':checked') == false) {
						$(ele).find('input[type=checkbox]').click();
					}
				});
			} else {
				$(e.target).parents('.kdpers_list').find('.kdpers_parentnode').each(function(i, ele) {
					if($(ele).data('id') != '0' && $(ele).find('input[type=checkbox]').is(':checked') == true) {
						$(ele).find('input[type=checkbox]').click();
					}
				});
			}
		} else {
			if(checked == true) {
				$(e.target).parents('.kdpers_list').find('.kdpers_parentnode').each(function(i, ele) {
					if($(ele).data('id') != '0' && $(ele).find('input[type=checkbox]').is(':checked') == false) {
						allChecked = false;
						return;
					}
				});

				if(allChecked == true) {
					$(e.target).parents('.kdpers_list').find('.kdpers_parentnode[data-id=0] input[type=checkbox]').prop("checked", true);
				}
				this.addFromSelectedUser($(e.target).parents('.kdpers_parentnode').data('id'), this.addOrgToSelectedOrgs.bind(this));
			} else {
				$(e.target).parents('.kdpers_list').find('.kdpers_parentnode[data-id=0] input[type=checkbox]').prop("checked", false);
				this.removeFromSelectedUser($(e.target).parents('.kdpers_parentnode').data('id'), this.removeOrgToSelectedOrgs.bind(this));
			}
		}

	};

	userList.prototype.orgCheck = function(e) {
		console.log(e);
		var checked = $(e.target).is(':checked');
		if(checked == true) {
			$(e.target).parents('.kdpers_parentnode').find('.kdpers_chatlist li').each(this.checkedUser.bind(this));
		} else {
			$(e.target).parents('.kdpers_parentnode').find('.kdpers_chatlist li').each(this.unCheckedUser.bind(this));
		}
	};

	// 选择用户事件
	userList.prototype.checkedUser = function(i, ele) {
		this.addFromSelectedUser($(ele).data('id'), this.addUserToSelectedUsers.bind(this));
		$(ele).find('input[type=checkbox]').prop("checked", true);
	};

	// 取消选择用户事件
	userList.prototype.unCheckedUser = function(i, ele) {
		this.removeFromSelectedUser($(ele).data('id'), this.removeUserToSelectedUsers.bind(this));
		$(ele).find('input[type=checkbox]').prop("checked", false);
	};

	// 绑定点击用户事件
	userList.prototype.bindUserCheck = function() {
		this.$element.on('click', '.nav-tabs-horizontal .kdpers_chatlist .kdpers_checkbox input[type=checkbox]', this.userCheck.bind(this));
		this.$element.on('click', '.kd_search_body .kdpers_chatlist .kdpers_checkbox input[type=checkbox]', this.searchUserCheck.bind(this));

		this.$element.on('click', '.kdpers_chatlist li', function(e) {
			$(this).find('input[type=checkbox]').click();
		});
	};

	// 绑定选择人员删除事件
	userList.prototype.bindSelectedUserDelete = function() {
		this.$element.on('click', '.user_sept_group_user .btn_delete', function(e) {
			var currentTenantOrOtherTenantSelectedUser = $(this).parents('.row:eq(0)').find('.nav-tabs-horizontal .kdpers_chatlist li[data-id=' + $(this).parents('.sept_message').attr('id') + '] input[type=checkbox]');
			var searchSelectedUser = $(this).parents('.row:eq(0)').find('.kd_search_body .kdpers_chatlist li[data-id=' + $(this).parents('.sept_message').attr('id') + '] input[type=checkbox]');
			if(currentTenantOrOtherTenantSelectedUser.is(':checked')) {
				currentTenantOrOtherTenantSelectedUser.click();
			}
			if(searchSelectedUser.is(':checked')) {
				searchSelectedUser.click();
			}
			$(this).parents('.sept_message').remove();
		});
	};

	// 绑定选择门店删除事件
	userList.prototype.bindSelectedTenantDelete = function() {
		this.$element.on('click', '.user_sept_group_tenant .btn_delete', function(e) {
			var selectedTenant = $(this).parents('.row:eq(0)').find('.nav-tabs-horizontal .kdpers_list li[data-id=' + $(this).parents('.sept_message').attr('id') + '] input[type=checkbox]');
			if(selectedTenant.is(':checked')) {
				selectedTenant.click();
			}
			$(this).parents('.sept_message').remove();
		});
	};

	// 绑定选择部门删除事件
	userList.prototype.bindSelectedOrgDelete = function() {
		this.$element.on('click', '.user_sept_group_org .btn_delete', function(e) {
			var selectedOrg = $(this).parents('.row:eq(0)').find('.nav-tabs-horizontal .kdpers_list li[data-id=' + $(this).parents('.sept_message').attr('id') + '] input[type=checkbox]');
			if(selectedOrg.is(':checked')) {
				selectedOrg.click();
			}

			$(this).parents('.sept_message').remove();
		});
	};

	// 添加用户到已选择人员列表
	userList.prototype.addUserToSelectedUsers = function(accountId) {
		var user = getUserInfo(accountId);
		if(user) {
			var imgSrc = "";
			if(user.HeadImgAddress && user.HeadImgAddress !== "") {
				imgSrc = user.HeadImgAddress;
			} else {
				imgSrc = this.options.defaultImgSrc;
			}

			this.$element.find('.user_sept_group_user').append(['<div id="' + accountId + '" class="sept_message">',
				'<div class="sept_user_msg">',
				'<a class="btn_delete"><i class="glyphicon glyphicon-remove"></i></a>',
				'<div class="user_img bg-green"><img src="' + imgSrc + '" /></div>',
				'<p>' + user.nick + '</p>',
				'</div>',
				'</div>'
			].join(''));
		}
		console.log('addUserToSelectedUsers');
	};

	// 添加门店到已选择门店列表
	userList.prototype.addTenantToSelectedTenants = function(tenantId) {
		console.log('addTenantToSelectedTenants:tenantId:' + tenantId);
		var tenant = getTenantInfo(tenantId);
		console.log(tenant);
		if(tenant) {
			this.$element.find('.user_sept_group_tenant').append(['<div id="' + tenantId + '" class="sept_message">',
				'<div class="sept_user_msg">',
				'<a class="btn_delete"><i class="glyphicon glyphicon-remove"></i></a>',
				'<div class="user_img bg-blue"><i class="fa fa-group"></i></div>',
				'<p>' + tenant.name + '</p>',
				'</div>',
				'</div>'
			].join(''));
		}
		console.log('addTenantToSelectedTenants');
	};

	// 添加门店到已选择门店列表
	userList.prototype.addOrgToSelectedOrgs = function(orgId) {
		var org = getOrgInfo(orgId);
		if(org) {
			this.$element.find('.user_sept_group_org').append(['<div id="' + orgId + '" class="sept_message">',
				'<div class="sept_user_msg">',
				'<a class="btn_delete"><i class="glyphicon glyphicon-remove"></i></a>',
				'<div class="user_img bg-blue"><i class="fa fa-group"></i></div>',
				'<p>' + org.name + '</p>',
				'</div>',
				'</div>'
			].join(''));
		}
	};

	// 删除用户从已选择人员列表中
	userList.prototype.removeUserToSelectedUsers = function(accountId) {
		this.$element.find('.user_sept_group_user #' + accountId).remove();
	};

	// 删除门店从已选择门店列表中
	userList.prototype.removeTenantToSelectedTenants = function(accountId) {
		this.$element.find('.user_sept_group_tenant #' + accountId).remove();
	};

	// 删除部门从已选择部门列表中
	userList.prototype.removeOrgToSelectedOrgs = function(accountId) {
		this.$element.find('.user_sept_group_org #' + accountId).remove();
	};

	// 用户点击事件
	userList.prototype.userCheck = function(e) {
		e.stopPropagation();
		var checked = $(e.target).is(':checked');
		var allChecked = true;
		if(checked == true) {
			$(e.target).parents('.kdpers_parentnode').find('.kdpers_chatlist li').each(function(i, ele) {
				if($(ele).find('input[type=checkbox]').is(':checked') == false) {
					allChecked = false;
					return;
				}
			});

			if(allChecked == true) {
				$(e.target).parents('.kdpers_parentnode').find('.kdpers_title input[type=checkbox]').prop("checked", true);
			}

			this.addFromSelectedUser($(e.target).parent().parent().data('id'), this.addUserToSelectedUsers.bind(this));

			console.log('userCheck.true');
		} else {
			$(e.target).parents('.kdpers_parentnode').find('.kdpers_title input[type=checkbox]').prop("checked", false);
			this.removeFromSelectedUser($(e.target).parent().parent().data('id'), this.removeUserToSelectedUsers.bind(this));

			console.log('userCheck.false');
		}
		console.log('userCheck');
	}

	// 用户点击事件
	userList.prototype.searchUserCheck = function(e) {
		e.stopPropagation();
		var checked = $(e.target).is(':checked');
		if(checked == true) {
			this.addFromSelectedUser($(e.target).parent().parent().data('id'), this.addUserToSelectedUsers.bind(this));
		} else {
			this.removeFromSelectedUser($(e.target).parent().parent().data('id'), this.removeUserToSelectedUsers.bind(this));
		}
		var currentTenantOrOtherTenantSelectedUser = $(e.target).parents('.row:eq(0)').find('.nav-tabs-horizontal .kdpers_chatlist li[data-id=' + $(e.target).parents('.kdmini_childnode').data('id') + '] input[type=checkbox]');
		if(currentTenantOrOtherTenantSelectedUser.is(':checked') != checked) {
			currentTenantOrOtherTenantSelectedUser.click();
		}
	}

	userList.prototype.bindOrgtoggle = function() {
		this.$element.on('click', '.kdpers_title h5', function(e) {
			if($(this).find(".fa").hasClass("fa-caret-right")) { //判断当前元素箭头是否向右
				$(this).find(".fa").removeClass("fa-caret-right").addClass("fa-caret-down"); //箭头向右的话，点击后箭头向下
			} else {
				$(this).find(".fa").removeClass("fa-caret-down").addClass("fa-caret-right"); //箭头向下的话，点击后箭头向右
			}
			$(this).parents('.kdpers_parentnode').find('.kdpers_chatlist').toggleClass('hidden');
		});
	};

	userList.prototype.bindUserDoubleClick = function() {
		this.$element.on('dblclick', '.kdpers_chatlist li', this.userDoubleClick.bind(this));
	};

	userList.prototype.bindSearchClose = function() {
		this.$element.on('click', '.btn-serach', function(e) {
			$('.search').val('');
			$('.search').keyup();
		})
	};

	userList.prototype.bindSearchTenantClose = function() {
		this.$element.on('click', '.btn-search-tenant', function(e) {
			$('.search-tenant').val('');
			$('.search-tenant').keyup();
		})
	};

	userList.prototype.bindSearchOrgClose = function() {
		this.$element.on('click', '.btn-search-org', function(e) {
			$('.search-org').val('');
			$('.search-org').keyup();
		})
	};

	userList.prototype.userDoubleClick = function(e) {
		// 获取所有选择项
		this.selectedUsers = [];

		var id = $(e.target).data('id');
		var name = $(e.target).data('name')
		if(id == undefined) {
			id = $(e.target).parents('li').first().data('id');
			name = $(e.target).parents('li').first().data('name');
		}

		// 选择人员
		this.selectedUsers.push({
			id: id,
			name: name
		});

		if(this.options.success) {
			this.options.success(this.selectedUsers, this.tags);
		}

		layer.close(this.options.layerIndex); //如果设定了yes回调，需进行手工关闭
	}

	var logError = function(message) {
		if(window.console) {
			window.console.error(message);
		}
	};

	$.fn[pluginName] = function(options) {

		var result;

		this.each(function() {
			var _this = $.data(this, pluginName);
			if(typeof options === 'string') {
				if(!_this) {
					logError('Not initialized, can not call method : ' + options);
				} else if(!$.isFunction(_this[options]) || options.charAt(0) === '_') {
					logError('No such method : ' + options);
				}
			} else if(typeof options === 'boolean') {
				result = _this;
			} else {
				$.data(this, pluginName, new userList(this, $.extend(true, {}, options)));
			}
		});

		return result || this;
	};

	// 获取人员信息
	function getUserInfo(accountId) {
		// 本门店人员
		for(var i = contactsObject.friends.length - 1; i >= 0; i--) {
			if(contactsObject.friends[i].account == accountId) {
				return contactsObject.friends[i];
			}
		};
		// 其他门店人员
		for(var i = contactsObject.qita.length - 1; i >= 0; i--) {
			if(contactsObject.qita[i].account == accountId) {
				return contactsObject.qita[i];
			}
		};
		// 搜索列表人员
		for(var i = contactsObject.search.length - 1; i >= 0; i--) {
			if(contactsObject.search[i].account == accountId) {
				return contactsObject.search[i];
			}
		};
		return false;
	}

	// 获取门店信息
	function getTenantInfo(tenantId) {
		console.log(contactsObject.tenants);
		// 门店
		for(var i = contactsObject.tenants.length - 1; i >= 0; i--) {
			if(contactsObject.tenants[i].id == tenantId) {
				return contactsObject.tenants[i];
			}
		};
		return false;
	}

	// 获取部门信息
	function getOrgInfo(orgId) {
		console.log(contactsObject.orgs);
		// 部门
		for(var i = contactsObject.orgs.length - 1; i >= 0; i--) {
			if(contactsObject.orgs[i].id == orgId) {
				return contactsObject.orgs[i];
			}
		};
		return false;
	}

})(jQuery, window, document);